#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
    int fd[2] = {0};
    int ret = pipe(fd);
    pid_t id = fork();
    if (id == 0)
    {
        // 子进程
        int cnt = 0;
        close(fd[0]);
        while (1)
        {

            char buffer[1024];
            snprintf(buffer, sizeof(buffer), "child of PID:%d，cnt:%d", getpid(), cnt++);
            int ret = write(fd[1], buffer, sizeof(buffer));
            /* if(ret>0)
            {
                std::cout<<"success"<<std::endl;
            }
            else{
                std::cout<<"fail"<<std::endl;
            } */
            sleep(5);
            break;
        }

        exit(0);
    }
    // 父进程
    close(fd[1]);

    while (1)
    {
        char read_buffer[1024] = {0};
        int ret = read(fd[0], read_buffer, sizeof(read_buffer) - 1);
        read_buffer[ret] = '\0';
        if (ret == 0)
        {
            std::cout << "写入端关闭，读端退出！" << std::endl;
            break;
        }
        else if (ret > 0)
        {
            if (read_buffer[ret - 1] == '\n')
            {
                read_buffer[ret - 1] = '\0';
            }
            std::cout << read_buffer << std::endl;
        }
        else
        {
            std::cout << "read fail!" << std::endl;
        }
    }
    int n;
    waitpid(id, &n, 0);
    return 0;
}